package org.grow.took.service;

import javafx.beans.binding.BooleanExpression;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

/**
 * @Author: xwg
 * @CreateDate: 2021/10/6
 */

@Service
public class PermissionDecision implements AccessDecisionManager , AccessDeniedHandler {

    @Override
    public void decide(Authentication authentication, Object o,
                       Collection<ConfigAttribute> collection)
            throws AccessDeniedException, InsufficientAuthenticationException {
// 主战场
        Collection<? extends GrantedAuthority> rolesFromUser = authentication.getAuthorities();
        Collection<ConfigAttribute> rolesFromUrl = collection;
        System.out.println("决策函数："+rolesFromUser);
        System.out.println("决策函数："+rolesFromUrl);
        Boolean result = false;
        for (GrantedAuthority grantedAuthority : rolesFromUser) {
            for (ConfigAttribute configAttribute : rolesFromUrl) {
                if (grantedAuthority.getAuthority().equals(configAttribute.getAttribute())){
                    System.out.println("允许当前用户访问");
                    result = true;
                    break;
                }
            }
        }
        if (!result){
            throw new AccessDeniedException("当前用户不能访问该url");
        }

    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }

    @Override
    public void handle(HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse,
                       AccessDeniedException e) throws IOException, ServletException {
//        处理一下异常
        httpServletResponse.setStatus(711);
        httpServletResponse.getWriter().println(e.getMessage());

    }
}
